import {login} from '@/services/ant-design-pro/api';
import {
  LockOutlined,
  MobileOutlined,
  UserOutlined,
} from '@ant-design/icons';
import {
  LoginFormPage,
  ProConfigProvider,
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import {useIntl, useModel} from '@umijs/max';
import {Alert,message, theme} from 'antd';
import {useState} from 'react';
import {flushSync} from 'react-dom';
import useStyles from '../register-result/style.style';
// @ts-ignore
import fmt from './images/fmt.webp'
// @ts-ignore
import video from './images/video.mp4'
// import logo from './images/logo.png'
import './index.less'

type LoginType = 'phone' | 'account';

const LoginMessage: React.FC<{
  content: string;
}> = ({content}) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Page = () => {
  const [loginType, setLoginType] = useState<LoginType>('account');
  const {token} = theme.useToken();
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  const [type, setType] = useState<string>('email');
  const {initialState, setInitialState} = useModel('@@initialState');
  const {styles} = useStyles();
  const intl = useIntl();

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };

  const handleSubmit = async (values: API.LoginParams) => {
    try {
      // 登录
      const res = await login({...values, type});

      if (res.code === 0) {
        window.localStorage.setItem('token', res.data?.token)
        window.localStorage.setItem('userid', res.data?.id)
        const defaultLoginSuccessMessage = intl.formatMessage({
          id: 'pages.login.success',
          defaultMessage: '登录成功！',
        });
        message.success(defaultLoginSuccessMessage);
        await fetchUserInfo();
        const urlParams = new URL(window.location.href).searchParams;
        window.location.href = urlParams.get('redirect') || '/';
        return;
      }
      // console.log(msg);
      // 如果失败去设置用户错误信息
      setUserLoginState(res);
    } catch (error) {
      const defaultLoginFailureMessage = intl.formatMessage({
        id: 'pages.login.failure',
        defaultMessage: '登录失败，请重试！',
      });
      console.log(error);
      message.error(defaultLoginFailureMessage);
    }
  };

  const {code = 0, data} = userLoginState;

  return (
    <div
      style={{
        // backgroundColor: 'white',
        height: '100vh',
      }}
    >
      <LoginFormPage
        backgroundImageUrl={fmt}
        // logo={logo}
        backgroundVideoUrl={video}
        title="比特币管理"
        containerStyle={{
          // backgroundColor: 'rgba(0, 0, 0,0.65)',
          // backdropFilter: 'blur(4px)',
        }}
        subTitle="比特币管理"
        initialValues={{
          autoLogin: true,
          // phone: 19938570370,
          // pwd: 123456
        }}
        onFinish={async (values) => {
          await handleSubmit(values as API.LoginParams);
        }}
      >
        {/*<Tabs*/}
        {/*  centered*/}
        {/*  activeKey={loginType}*/}
        {/*  onChange={(activeKey) => {*/}
        {/*    setLoginType(activeKey as LoginType)*/}
        {/*    setUserLoginState({})*/}
        {/*  }}*/}
        {/*>*/}
        {/*  <Tabs.TabPane key={'account'} tab={'账号密码登录'}/>*/}
        {/*  /!*<Tabs.TabPane key={'phone'} tab={'手机号登录'}/>*!/*/}
        {/*</Tabs>*/}
        {code !== 0 && loginType === 'account' && (
          <LoginMessage
            content={intl.formatMessage({
              id: 'pages.login.accountLogin.errorMessage',
              defaultMessage: '账户或密码错误',
            })}
          />
        )}
        {loginType === 'account' && (
          <>
            <ProFormText
              name="value"
              fieldProps={{
                size: 'large',
                prefix: (
                  <UserOutlined
                    style={{
                      color: token.colorText,
                    }}
                    className={'prefixIcon'}
                  />
                ),
              }}
              placeholder={'邮箱'}
              rules={[
                {
                  required: true,
                  message: '请输入邮箱!',
                },
              ]}
            />
            <ProFormText.Password
              name="passwd"
              fieldProps={{
                size: 'large',
                prefix: (
                  <LockOutlined
                    style={{
                      color: token.colorText,
                    }}
                    className={'prefixIcon'}
                  />
                ),
              }}
              placeholder={'密码'}
              rules={[
                {
                  required: true,
                  message: '请输入密码！',
                },
              ]}
            />
          </>
        )}

        {code !== 0 && loginType === 'phone' && <LoginMessage content="验证码错误"/>}
        {loginType === 'phone' && (
          <>
            <ProFormText
              fieldProps={{
                size: 'large',
                prefix: (
                  <MobileOutlined
                    style={{
                      color: token.colorText,
                    }}
                    className={'prefixIcon'}
                  />
                ),
              }}
              name="mobile"
              placeholder={'手机号'}
              rules={[
                {
                  required: true,
                  message: '请输入手机号！',
                },
                {
                  pattern: /^1\d{10}$/,
                  message: '手机号格式错误！',
                },
              ]}
            />
            <ProFormCaptcha
              fieldProps={{
                size: 'large',
                prefix: (
                  <LockOutlined
                    style={{
                      color: token.colorText,
                    }}
                    className={'prefixIcon'}
                  />
                ),
              }}
              captchaProps={{
                size: 'large',
              }}
              placeholder={'请输入验证码'}
              captchaTextRender={(timing, count) => {
                if (timing) {
                  return `${count} ${'获取验证码'}`;
                }
                return '获取验证码';
              }}
              name="captcha"
              rules={[
                {
                  required: true,
                  message: '请输入验证码！',
                },
              ]}
              onGetCaptcha={async () => {
                message.success('获取验证码成功！验证码为：1234');
              }}
            />
          </>
        )}
        <div
          style={{
            marginBlockEnd: 24,
          }}
        >
          <ProFormCheckbox noStyle name="autoLogin">
            自动登录
          </ProFormCheckbox>
          {/*<a*/}
          {/*  style={{*/}
          {/*    float: 'right',*/}
          {/*  }}*/}
          {/*>*/}
          {/*  忘记密码*/}
          {/*</a>*/}
        </div>
      </LoginFormPage>
    </div>
  );
};

export default () => {
  return (
    <ProConfigProvider >
      <Page/>
    </ProConfigProvider>
  );
};
